import java.sql.SQLOutput;
import java.util.Arrays;

public class graphByMatrix {
    //使用邻接矩阵来存储图
    private char[] arrayV;//顶点数组
    private int[][] matrix;//矩阵
    private boolean isDirect;//是否是有向图
    //size代表当前顶点个数
    public graphByMatrix(int size,boolean isDirect ){
        this.arrayV=new char[size];//放入的顶点个数
        matrix=new int[size][size];//初始化二位数组matrix的个数
        for (int i=0;i<size;i++){
            Arrays.fill(matrix[i],Constant.MAX);//以指定值填充第一维数组
        }
        this.isDirect=isDirect;
    }
    //初始化顶点数组
    public void initArrayV(char[] array){
        for (int i=0;i<array.length;i++){
            arrayV[i]=array[i];
        }
    }
    /*srcV 起点
    * destV 终点
    * weight 权值*/
    public void addEdge(char srcV,char destV,int weight){
        int srcIndex=getIndexOfv(srcV);
        int destIndex=getIndexOfv(destV);
        matrix[srcIndex][destIndex]=weight;
        //如果是无向图
        if (isDirect==false){
            matrix[destIndex][srcIndex]=weight;
        }
    }
    //获取顶点下标
    private int getIndexOfv(char v){
        for (int i = 0; i < arrayV.length; i++) {
            if (arrayV[i]==v){
                return i;
            }
        }
        return -1;
    }

    //打印图
    public void printGraph(){
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix.length;j++){
                if (matrix[i][j]==Constant.MAX){
                    System.out.print("无穷大 ");
                }else{
                    System.out.print(matrix[i][j]+" ");
                }
            }
            System.out.println();
        }
    }

    //获取顶点的度
    //有向图=入度+出度
    public int getDevOfV(char v){
        int count=0;
        int srcIndex=getIndexOfv(v);//获取下标
        for (int i=0;i<arrayV.length;i++){
            if (matrix[srcIndex][i]!=Constant.MAX){
                count++;
            }
        }
        //无向图的度计算完成
        //有向图，上述循环相当于计算出度
        //计算有向图的入度
        if (isDirect){
            for (int i = 0; i < arrayV.length; i++) {
                if (matrix[i][srcIndex]!=Constant.MAX){
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        char[] chars={'A','B','C','D'};
        graphByMatrix graph=new graphByMatrix(chars.length,true);
        graph.initArrayV(chars);

        graph.addEdge('A','B',1);
        graph.addEdge('A','D',1);
        graph.addEdge('B','A',1);
        graph.addEdge('B','C',1);
        graph.addEdge('C','B',1);
        graph.addEdge('C','D',1);
        graph.addEdge('D','A',1);
        graph.addEdge('D','C',1);
        graph.printGraph();
        System.out.println("_____________________");
        System.out.println(graph.getDevOfV('A'));
    }


}
